import DBLItem from "./DBLItem";

import {
    C2S_FINISH_AD,
    L2EProtocol,
    S2CProtocol,
    S2C_FINISH_AD,
    S2C_REQ_AD_CODE
} from "../proto/ELProtocol";
import { 
    commonPost, getAdGuideUrl, finishAdUrl, 
    goFightingUrl,battleResultUrl,
    trmbAdCode, clearAdCode, reliveAdCode,
    adCoolDur
} from "../utils/CommonUtils";

import {
    NotificationCenter 
} from "../utils/NotificationCenter";
import { C2S_REQ_AD_CODE } from "../../../assets_err/Script/proto/ELProtocol";


const {ccclass, property} = cc._decorator;

@ccclass
export default class Game extends cc.Component {

    @property(cc.Label)
    label: cc.Label = null;

    
    @property(cc.Prefab)
    dblItem: cc.Prefab = null;

    // private sprit1:cc.Node = null;
    // private sprit2:cc.Node = null;
    // private sprit3:cc.Node = null;
    // private spritBing:cc.Node = null;
    // private spritJing:cc.Node = null;
    // private spritChai:cc.Node = null;

    //TODO  测试显示 ------------------------------
    private ad_layout:cc.Node = null;

    //----------------------------------
    //粒子
    //----------------------------------
    private boluosuil_Particle:cc.Node = null;
    private boluosuil_Particle1:cc.Node = null;
    private boluosuil_Particle2:cc.Node = null;

    private baozaquan_Particle:cc.Node = null;
    private baozazhong_Particle:cc.Node = null;
    private hechengxiao_Particle:cc.Node = null;



    //数值
    private score_lbl:cc.Label = null;//主界面分数
    private score_lbl2:cc.Label = null;//暂停界面分数
    private score_lbl3:cc.Label = null;//结算界面分数 (结算界面)
    private rmb_lbl:cc.Label = null;     //游戏过程中  获得红包数量
    private rmb_fixed_lbl:cc.Label = null;//关卡通关需要 获得红包数量
    private boluo_lbl:cc.Label = null;//游戏过程中  获得菠萝的数量 (结算界面)
    private lbl_max_com:cc.Label = null;// 最高连击(结算界面)
    private lbl_max_score:cc.Label=null;// 历史最高分(结算界面)

    private curGameScore:number = 0;//玩家分数
    private curGameMaxBob:number = 0;//玩家最高连炸数
    private curBLCount:number = 0;//玩家游戏中菠萝数量
    private curRMBCount:number = 0;//玩家红包碎片

    //服务端数据 不变
    private historyMaxScore:number = 0;//玩家历史最高分数
    private battleRMBCount:number = 0;//关卡通关需要 获得红包数量

    //游戏中统计限制
    private itemBingLiveCount:number = 0;
    //private itemRMBLiveCount:number = 0;

    //layerout 容器
    private sparr_layout:cc.Node = null;
    private gameover_layout:cc.Node = null;
    private gamesuspend_layout:cc.Node = null;
    private bottom_layout:cc.Node = null;


    //位置计算相关
    private centerToRight:number = 0;//中心点 向右偏移 10 像素
    private leftSpace:number = 0;//左边栏宽
    private bottomSpace:number = 0;//底部栏宽

    private ox:number = 0;
    private oy:number = 0;
    private spaceX:number = 5;
    private spaceY:number = 0;

    private spW:number = 132;
    private spH:number = 132;


    private maxy:number = 0;
    private miny:number = 0;

    private maxRows:number = 8;//每屏的行
    private maxCols:number = 4;//每屏的列

    
    //private checkPostion:boolean = false;
    //private lastTime:number = 0;
    //private passTime:number = 1000;

    
    private gameOver:boolean = false;
    public moveGrowNum:number = 0;
    public moveSpaceNum:number = 4;
    public hasChangeMoveSpaceNum:boolean = false;
    private stopUpate:boolean = false;
    private showGameOver:boolean = false;
    //移动相关 数值
    public moveBaseSpeed:number= 0;// 移动基础速度
    public startMoveBaseSpeed:number= 0.8;// 移动基础速度
    public fastMoveBaseSpeed:number= 4;// 移动基础速度
    private finishFastMoving:boolean = false;

    public moveMult:number= 1;//移动倍速初始值
    public moveMultAdd:number=0.07;//移动倍速 增长

    private highScreenNum:number = 2;//高级屏开始数
    private highScreen:boolean = false;//高级屏
    private fristScreen:boolean = true;//第一屏
    private screenNum:number = 0;//屏幕数

    
    private nextScreenAddY:number = 0;
    private nextScreen:boolean = false;
    //private passRowNum:number = 0;

    private totalRowNum:number = 0;
    
    public outScreenY:number = 0;
    private moveNextY:number = 0;//纵向移动一格的长度



    private gameKey:string = "";
    private svalue:string = "";

    //上次点击的item
    //private lastClickItem:any=null;
    onLoad () {
        NotificationCenter.Instance.on("goFightingHandler", this.goFighting, this);
        NotificationCenter.Instance.on("battleResultHandle", this.battleResult, this);
        NotificationCenter.Instance.on("getAdGuideHandle", this.getAdGuideHandle, this);
        NotificationCenter.Instance.on("requestFinishAd", this.requestFinishAd, this);
        NotificationCenter.Instance.on("finishAdHandle", this.finishAdHandle, this);
        NotificationCenter.Instance.on("serviceClosedAd", this.serviceClosedAd, this);
    }
    onDestroy() {
        NotificationCenter.Instance.off("goFightingHandler", this.goFighting, this);
        NotificationCenter.Instance.off("battleResultHandle", this.battleResult, this);
        NotificationCenter.Instance.off("getAdGuideHandle", this.getAdGuideHandle, this);
        NotificationCenter.Instance.off("requestFinishAd", this.requestFinishAd, this);
        NotificationCenter.Instance.off("finishAdHandle", this.finishAdHandle, this);
        NotificationCenter.Instance.on("serviceClosedAd", this.serviceClosedAd, this);        
    }


    start () {

        this.stopUpate = true;

        // init logic
        console.log("start ... ...");
        this.sparr_layout = cc.find("sparr_layout",this.node);
        this.gameover_layout = cc.find("gameover_layout",this.node);
        this.gamesuspend_layout = cc.find("gamesuspend_layout",this.node);

        this.bottom_layout = cc.find("bottom_layout",this.node);
        this.bottomSpace = this.bottom_layout.height/2;

        //广告
        this.ad_layout = cc.find("ad_layout",this.node);

        //粒子
        this.boluosuil_Particle = cc.find("eff_layout/boluosuil",this.node);
        this.boluosuil_Particle1 = cc.find("eff_layout/boluosuil1",this.node);
        this.boluosuil_Particle2 = cc.find("eff_layout/boluosuil2",this.node);
        this.baozaquan_Particle = cc.find("eff_layout/baozaquan",this.node);
        this.baozazhong_Particle = cc.find("eff_layout/baozazhong",this.node);
        this.hechengxiao_Particle = cc.find("eff_layout/hechengxiao",this.node);

        
        //显示计分
        this.score_lbl = cc.find("bottom_layout/zhandou_jifen/lbl_score",this.node).getComponent(cc.Label);
        this.score_lbl2 = cc.find("gamesuspend_layout/lbl_score",this.node).getComponent(cc.Label);
        this.score_lbl3 = cc.find("gameover_layout/lbl_score",this.node).getComponent(cc.Label);
        this.lbl_max_score = cc.find("gameover_layout/lbl_max_score",this.node).getComponent(cc.Label);
        //红包
        this.rmb_lbl = cc.find("bottom_layout/zhandou_jifen/lbl_rmb",this.node).getComponent(cc.Label);
        this.rmb_fixed_lbl = cc.find("bottom_layout/zhandou_jifen/lbl_rmb_fixed",this.node).getComponent(cc.Label);
        //菠萝数
        this.boluo_lbl = cc.find("gameover_layout/boluo_lbl",this.node).getComponent(cc.Label);
        //连击数
        this.lbl_max_com = cc.find("gameover_layout/lbl_max_com",this.node).getComponent(cc.Label);

       // this.ox = 0;//(cc.winSize.width/2) * -1 + this.centerToRight;
        this.ox = (this.leftSpace + (this.spW*2) + this.spaceX*1.5) * -1;

        this.oy = (cc.winSize.height/2);

        this.outScreenY = (this.oy) - (this.spH+this.spaceY);
        this.moveNextY=this.spH+this.spaceY;

        this.nextScreenAddY = cc.winSize.height*0.2;

        this.maxy = (cc.winSize.height/2 - this.bottomSpace ) * -1;
        console.log("this.maxy: "+this.maxy);

        this.miny = this.oy - this.spH;

        //this.fristAddSP();
        //this.stopUpate = false;
        this.requestGoFighting();
    }



    update(){

        if(this.gameOver){
            if(!this.showGameOver){
                this.showGameOver = true;
                this.requestBattleResult();
            }
            return;
        }

        if(this.stopUpate){
            return;
        }



       //this.spH+30

        let removeArr:Array<cc.Node> = new Array<cc.Node>();

       // console.log("this.moveSpaceNum:"+this.moveSpaceNum)
        if(this.moveSpaceNum>=6){
            this.moveBaseSpeed = this.startMoveBaseSpeed;
            this.finishFastMoving = true;
        }

        //每帧移动的距离
        let tmpMoveNum:number = this.getMoveStep();

        this.moveGrowNum = this.moveGrowNum+tmpMoveNum;


        if(this.moveGrowNum>=this.moveNextY){
            this.moveGrowNum=0;
            this.moveSpaceNum++;
            this.hasChangeMoveSpaceNum=true;
            //console.log("this.moveSpaceNum:"+this.moveSpaceNum);
        }


        if(this.moveSpaceNum%this.maxRows==0){
            if(this.hasChangeMoveSpaceNum){
                this.nextScreen=true;
                this.screenNum++;
                this.moveMult = this.moveMult + this.moveMultAdd;
                this.hasChangeMoveSpaceNum=false;
            }
        }


        let hasRemove:boolean = false;
        let rsize:number = removeArr.length-1;
        for (let index=rsize; index>=0; index--) {
            removeArr[index].getComponent("DBLItem").hasRemoved=true;
            this.sparr_layout.removeChild(removeArr[index],true);
            hasRemove=true;
        }
        //if(hasRemove){
        //    this.passRowNum++;
        //}

        if(this.screenNum>=this.highScreenNum){
            this.highScreen=true;
        }

    
        //下一屏
        if(this.nextScreen){
            this.countNextRMBItemRowCol();
            if(this.highScreen){
                this.countNextBingItemRowCol();
            }
            //let allLv1Row:number = this.getRandomNumInt(1,this.maxRows);
            for(let y=1; y<=this.maxRows; y++){
                let highLvCol:number = this.getRandomNumInt(1,this.maxCols);
                for(let x=1; x<=this.maxCols; x++){
                    //this.addSP(y, x, cc.winSize.height-this.spH*1, allLv1Row,highLvCol)
                    this.addSP(y, x, cc.winSize.height-this.spH*1  + this.nextScreenAddY,/* allLv1Row,*/highLvCol)
                }
                this.totalRowNum++;
            }               
            this.nextScreen=false;
        }
        
    }

























    //---------------------------------------------------------------
    //添加   菠萝
    //---------------------------------------------------------------    
    private addSP(row:number, col:number, addy:number, highLvCol:number) {

        let sp:any = cc.instantiate(this.dblItem);
        sp.parent = this.sparr_layout;

        //console.log("增加菠萝row： "+row+" col:"+col);
        let tmpId:number = this.randItemId(row, col,  highLvCol);

        let gy:number = (this.oy*-1) + this.moveNextY*row  + addy;

        sp.setPosition(this.ox + this.leftSpace + (this.spW*(col-1)) + this.spaceX*(col-1) + this.spW/2, gy);



        //console.log("col："+col+" x:"+sp.x)

        let data:any = {};
        data.id=tmpId;
        data.row=this.totalRowNum;
        data.col=col;
        data.gameComponent=this;
        sp.getComponent("DBLItem").initView(data);


        //TODO 取消点击事件
       // sp.on(cc.Node.EventType.TOUCH_START, this.onTouchStartCallback, this, true);

        col++;      

    }



























    //-----------------------------------------------------------
    //合并  爆炸  相关方法
    //-----------------------------------------------------------
    public checkMerge(id:Number,toRow:Number,toCol:Number){

        

        let canMergeItem:any = null;
        //console.log("合并 id： "+id+" row: "+toRow+" col: "+toCol);
        for(let i=0; i<this.sparr_layout.children.length;i++){
            let item:any = this.sparr_layout.children[i];

            let cid:Number = item.getComponent("DBLItem").id;
            let cRow:Number = item.getComponent("DBLItem").row;
            let cCol:Number = item.getComponent("DBLItem").col;
            
            
            if(id==cid && toRow==cRow && toCol==cCol){
                canMergeItem = item;
                return canMergeItem;
            }
        }
        return canMergeItem;
    }

    private playParticleEff(particle:any, item:any){
         particle.x=item.x;
         particle.y=item.y;
         particle.active=true;
         particle.getComponent(cc.ParticleSystem).resetSystem();
    }

    public doMergeItemAction(item:any,removeCol:number,moveRow:number,remiveItem:any){
        this.stopUpate=true;

        remiveItem.getComponent("DBLItem").hasRemoved=true;
        this.sparr_layout.removeChild(remiveItem,true);

        let cid:number = item.getComponent("DBLItem").id;
        let cRow:number = item.getComponent("DBLItem").row;
        let cCol:number = item.getComponent("DBLItem").col;

        //升级
        let data:any = {};
        data.id=cid+1;
        data.row=cRow;
        data.col=cCol;
        data.gameComponent=this;
        item.getComponent("DBLItem").updateView(data);

        

        if(data.id==DBLItem.ID_2){
            // this.hechengxiao_Particle.x=item.x;
            // this.hechengxiao_Particle.y=item.y;
            // this.hechengxiao_Particle.active=true;
            // this.hechengxiao_Particle.getComponent(cc.ParticleSystem).resetSystem();
            this.playParticleEff(this.hechengxiao_Particle, item)

            //计分
            this.curGameScore = this.curGameScore+10;
            this.score_lbl.string = this.curGameScore+"";
            this.score_lbl2.string = this.curGameScore+"";
            this.score_lbl3.string = this.curGameScore+"";

            //this.show_result_lbl.string = "得分："+10

        }else if(data.id==DBLItem.ID_3){
            //  this.hechengxiao_Particle.x=item.x;
            //  this.hechengxiao_Particle.y=item.y;
            //  this.hechengxiao_Particle.active=true;
            //  this.hechengxiao_Particle.getComponent(cc.ParticleSystem).resetSystem();
            
            // this.baozazhong_Particle.x=item.x;
            // this.baozazhong_Particle.y=item.y;
            // this.baozazhong_Particle.active=true;
            // this.baozazhong_Particle.getComponent(cc.ParticleSystem).resetSystem();
            this.playParticleEff(this.baozazhong_Particle, item)
            this.playParticleEff(this.hechengxiao_Particle, item)

            //计分
            this.curGameScore = this.curGameScore+20;
            this.score_lbl.string = this.curGameScore+"";
            this.score_lbl2.string = this.curGameScore+"";
            this.score_lbl3.string = this.curGameScore+"";
            //this.show_result_lbl.string = "得分："+20
        }

        this.moveColItemsUPOnceByStep(removeCol,moveRow);
        //this.moveColItemsUPOnce(removeCol,cRow)
        //this.stopUpate=false;
    }

    //重新刷新  高度位置
    private fixedYposition(){
        let rowInfo:any = this.findRowInfo();
        let maxRowNum:number =  rowInfo[0];
        let minRowNum:number =  rowInfo[1];        
        let topY:number =  rowInfo[2];        

        for(let x=1; x<=this.maxCols; x++){
            let moveDown:number = 0;
            for(let y=maxRowNum; y>=minRowNum; y--){
                let ti = this.getItemByRowAndCol(x,y);
                if(ti!=null){
                    ti.y = topY - this.moveNextY*moveDown;
                }
                moveDown ++;
            }
        }
    }

    private moveColItemsUPOnceByStep(removeCol:number,moveRow:number){
        let moveItem:any = this.getItemByRowAndCol(removeCol,moveRow)
        if(moveItem!=null){
            moveItem.getComponent("DBLItem").row=moveItem.getComponent("DBLItem").row+1;
            moveItem.y = moveItem.y + this.moveNextY;
            moveItem.getComponent("DBLItem").curShowItem.y=moveItem.height * -1;
            cc.tween(moveItem.getComponent("DBLItem").curShowItem)
            .to(0.1, { position: cc.v2(0, 0) })
            .call(() => {
                this.moveColItemsUPOnceByStep(removeCol,moveRow-1);
            })
            .start();                
        }else{
            this.fixedYposition();
            this.stopUpate=false;
        }
    }


    //两个完整的 玻璃 合并， 链式爆炸
    public doMargeChainAction(item1:any, item2:any){
        this.stopUpate=true;

        let removeArr:Array<any> = new Array();//等待移除的item
        let checkArr:Array<any> = new Array(); //等待检测的item

        //let rmbArr:Array<any> = new Array();//红包碎片

        //checkArr.push(item1)
        checkArr.push(item2)
        //removeArr.push(item1);
        removeArr.push(item2);
        //直接remove 移动的item
        item1.getComponent("DBLItem").hasRemoved=true;
        this.sparr_layout.removeChild(item1,true);


        //计分
        let removeItem1Count:number = 0;
        let removeItem2Count:number = 0;
        let removeItem3Count:number = 2;
        let removeItemRMBCount:number = 0;

        //console.log("爆炸的瓜 检测----------------------------------------------------------");
        while(checkArr.length>0){
            let checkItem:any = checkArr.pop();
            let checkItemRow:number = checkItem.getComponent("DBLItem").row;
            let checkItemCol:number = checkItem.getComponent("DBLItem").col;


            //console.log("------------检查的完整瓜row： "+checkItemRow+" col:"+checkItemCol);

            //this.sparr_layout.children.forEach(element => {
            for(let i=0; i<this.sparr_layout.children.length;i++){
                let element:any = this.sparr_layout.children[i];
                
                if(this.isShowing(element.y)){
                    let tmpid = element.getComponent("DBLItem").id;
                    if(tmpid!=DBLItem.ID_BING){
                        if(tmpid.id!=DBLItem.ID_BING){  //冰西瓜不能移除
                            let inRemoveArr = removeArr.indexOf(element);
                            if(inRemoveArr<0){
                                let willRomveItemRow:number = element.getComponent("DBLItem").row;
                                let willRomveItemCol:number = element.getComponent("DBLItem").col;
            
                                let canRemove:boolean = this.rangeIn(checkItemRow,willRomveItemRow,checkItemCol,willRomveItemCol);
                                if(canRemove){
                                    removeArr.push(element);
                                    
                                    //console.log("##########爆炸的瓜row： "+willRomveItemRow+" col:"+willRomveItemCol);

                                    if(tmpid==DBLItem.ID_3){
                                        checkArr.push(element);
                                        removeItem3Count++;
                                    }else if(tmpid==DBLItem.ID_2){
                                        removeItem2Count++;
                                    }else if(tmpid==DBLItem.ID_1){
                                        removeItem1Count++;
                                    }else if(tmpid==DBLItem.ID_RMB){
                                        removeItemRMBCount ++;
                                    }
                                }
                            }
                        }
                    }
                }
            }   
        }
        //console.log("爆炸的瓜 检测----------------------------------------------------------");


        let rowInfo:any =  this.findRowInfo();
        let maxRowNum:number =  rowInfo[0];
        let minRowNum:number =  rowInfo[1];
        //console.log("maxRowNum: "+maxRowNum+"， minRowNum: "+minRowNum);

        //计分--------------------------------------------------------------------


        let tmpScore = 0;
        //2. 整瓜：整瓜数*35+半瓜数*17+1/4瓜数*8
        tmpScore = tmpScore + removeItem3Count*40+removeItem2Count*20+removeItem1Count*10;
        //瓜数大于等于5计算连炸加成：
        //公式=连炸瓜数^2*10
        let tmpmaxBob:number = 0;
        if(removeItem3Count>=5){
            tmpScore = tmpScore + removeItem3Count*removeItem3Count*10;
            tmpmaxBob = removeItem3Count;
        }

        //最高连接数量
        if(this.curGameMaxBob<tmpmaxBob){
            this.curGameMaxBob = tmpmaxBob;
        }
        this.lbl_max_com.string = this.curGameMaxBob+"";

        //计分
        this.curGameScore = this.curGameScore + tmpScore;
        this.score_lbl.string = this.curGameScore+"";
        this.score_lbl2.string = this.curGameScore+"";
        this.score_lbl3.string = this.curGameScore+"";

        //菠萝数量统计
        this.curBLCount = this.curBLCount+removeItem3Count;        
        this.boluo_lbl.string = this.curBLCount+"";

        //红包碎片获取
        this.curRMBCount = this.curRMBCount+removeItemRMBCount
        this.rmb_lbl.string = this.curRMBCount+""


        //爆炸处理

        // removeArr.forEach(element => {
        //     //TODO 增加爆炸效果

        //     //粒子效果
        //     if(element.getComponent("DBLItem").id==DBLItem.ID_3){
        //         this.playParticleEff(this.boluosuil_Particle, element)
        //         this.playParticleEff(this.boluosuil_Particle1, element)
        //         this.playParticleEff(this.boluosuil_Particle2, element)
    
        //         this.playParticleEff(this.baozazhong_Particle, element)
        //         this.playParticleEff(this.baozaquan_Particle, element)
        //     }

        //     element.getComponent("DBLItem").hasRemoved=true;
        //     this.sparr_layout.removeChild(element,true);
        // });

        let tmpRemoveArrIndex:number = removeArr.length;
        this.playChainEff(tmpRemoveArrIndex, removeArr, maxRowNum, minRowNum)
    }
    private playChainEff(tmpRemoveArrIndex:number, removeArr:Array<any>, maxRowNum:number, minRowNum:number){
        tmpRemoveArrIndex--;
        let tmpElement:any = removeArr[tmpRemoveArrIndex];
                //     //粒子效果
        if(tmpElement.getComponent("DBLItem").id==DBLItem.ID_3){
            cc.tween(this.node)
            .call(() => {
                this.playParticleEff(this.boluosuil_Particle, tmpElement)
                this.playParticleEff(this.boluosuil_Particle1, tmpElement)
                this.playParticleEff(this.boluosuil_Particle2, tmpElement)
    
                this.playParticleEff(this.baozazhong_Particle, tmpElement)
                this.playParticleEff(this.baozaquan_Particle, tmpElement)

                tmpElement.getComponent("DBLItem").hasRemoved=true;
                this.sparr_layout.removeChild(tmpElement,true);
            })
            .delay(0.2)
            .call(() => {
                let isFinish:boolean = this.checkPlayChainEffFinshed(tmpElement, tmpRemoveArrIndex, maxRowNum, minRowNum)
                if(!isFinish){
                    this.playChainEff(tmpRemoveArrIndex, removeArr, maxRowNum, minRowNum)
                }
            })
            .start();     
        }else{
            cc.tween(this.node)
            .delay(0.2)
            .call(() => {
                tmpElement.getComponent("DBLItem").hasRemoved=true;
                this.sparr_layout.removeChild(tmpElement,true);
                let isFinish:boolean = this.checkPlayChainEffFinshed(tmpElement, tmpRemoveArrIndex, maxRowNum, minRowNum)
                if(!isFinish){
                    this.playChainEff(tmpRemoveArrIndex, removeArr, maxRowNum, minRowNum)
                }
            })
            .start();     
        }


    }
    private checkPlayChainEffFinshed(tmpElement:any, tmpRemoveArrIndex:number, maxRowNum:number, minRowNum:number){



        //-----------------------------------------------------------------------------------------
        //表现结束的处理
        //------------------------------------------------------------------------------------------
        if(tmpRemoveArrIndex<=0){
            //TODO 上移  待优化------------------------------
            for(let tmpcol=1;tmpcol<=this.maxCols;tmpcol++){
                //let emptyRow:number = 0; 
                //console.log("检查第"+tmpcol+"列-----------------------------------------------");
                for(let tmprow=maxRowNum-1; tmprow>=minRowNum; tmprow--){
                    let ti = this.getItemByRowAndCol(tmpcol,tmprow);
                    //console.log("检查第"+tmprow+"行  ****************************");
                    if(ti!=null){
                        //console.log("第"+tmpcol+"列"+"第"+tmprow+"行item  尝试向上移动");
                        this.moveItemTop(tmpcol,maxRowNum, tmprow, ti);
                    }
                }
            }
            if(this.curRMBCount>=this.battleRMBCount){
                this.requestBattleResult()
            }else{
                this.stopUpate=false;
            }
            return true;
        }
        //------------------------------------------------------------------------------------------

        return false;
    }












    public doBombAction(){
        this.stopUpate=true;

        let removeArr:Array<any> = new Array();//等待移除的item
        //let rmbArr:Array<any> = new Array();//红包碎片

        this.itemBingLiveCount=0;

        //计分
        let removeItem1Count:number = 0;
        let removeItem2Count:number = 0;
        let removeItem3Count:number = 0;
        let removeItemRMBCount:number = 0;

        this.sparr_layout.children.forEach(element => {

            if(this.isShowing(element.y)){
                let tmpid = element.getComponent("DBLItem").id;

                let inRemoveArr = removeArr.indexOf(element);
                if(inRemoveArr<0 ){
                    removeArr.push(element);
                }
                //计分
                if(tmpid==DBLItem.ID_3){
                    removeItem3Count++;
                }else if(tmpid==DBLItem.ID_2){
                    removeItem2Count++;
                }else if(tmpid==DBLItem.ID_1){
                    removeItem1Count++;
                }else if(tmpid==DBLItem.ID_RMB){
                    removeItemRMBCount++;
                }                    

            }

        });     


        //计分--------------------------------------------------------------------
        if(this.curGameMaxBob<removeItem3Count){
            this.curGameMaxBob = removeItem3Count;
        }
        let tmpScore = 0;
        //2. 整瓜：整瓜数*35+半瓜数*17+1/4瓜数*8
        tmpScore = tmpScore + removeItem3Count*40+removeItem2Count*20+removeItem1Count*10;
        //瓜数大于等于5计算连炸加成：
        //公式=连炸瓜数^2*10
        let tmpString:string = "";
        if(removeItem3Count>=5){
            tmpScore = tmpScore + removeItem3Count*removeItem3Count*10;
            tmpString = "连炸： "+ removeItem3Count
        }
        tmpString = tmpString + " 得分："+tmpScore;
        //this.show_result_lbl.string = tmpString

        this.curGameScore = this.curGameScore + tmpScore;
        //红包碎片获取
        this.curRMBCount = this.curRMBCount+removeItemRMBCount
        this.rmb_lbl.string = this.curRMBCount+""


        removeArr.forEach(element => {
            //TODO 增加爆炸效果
            element.getComponent("DBLItem").hasRemoved=true;
            this.sparr_layout.removeChild(element,true);
            //element.destroy(); 
        });


        this.fixedYposition();
        this.stopUpate=false;
    }

















    //-----------------------------------------------------
    //计算查找  移动位置
    //-----------------------------------------------------
    private rangeIn(checkItemRow:number,willRomveItemRow:number,checkItemCol:number,willRomveItemCol:number){
        if(  (checkItemRow+1==willRomveItemRow||checkItemRow-1==willRomveItemRow||checkItemRow==willRomveItemRow) 
            && (checkItemCol+1==willRomveItemCol||checkItemCol-1==willRomveItemCol||checkItemCol==willRomveItemCol) ){

            return true;
        }
        return false;
    }
    //查找最大row item
    private findRowInfo(){
        let maxRow:number = 0;
        let minRow:number = -1;
        let topY = 0;
        this.sparr_layout.children.forEach(element => {
            if(this.isShowing(element.y)){
                let row1:number = element.getComponent("DBLItem").row;
                if(row1>maxRow){
                    maxRow=row1;
                    topY = element.y;
                }
                if(minRow==-1){
                    minRow=row1;
                }else{
                    if(row1<minRow){
                        minRow=row1;
                    }
                }
            }
        });     
        let data:any = [];
        data[0] = maxRow;
        data[1] = minRow;
        data[2] = topY;
        return data;
    }
    //查找item 
    private getItemByRowAndCol(col:number,row:number){
        for(let i=0; i<this.sparr_layout.children.length;i++){
            let item:any = this.sparr_layout.children[i];
            let row1:number = item.getComponent("DBLItem").row;
            let col1:number = item.getComponent("DBLItem").col;
            if(row1==row && col1==col){
                return item;
            }          
        }
        return null;
    }

    //-----------------------------------------------------
    //移动
    //-----------------------------------------------------
    public getMoveStep(){
        return this.moveBaseSpeed*this.moveMult;
    }
    public isShowing(itemY:number){
        if(itemY<this.outScreenY - (this.spH/2/2)){
            return true;
        }
        return false;
    }

    //向上移动一格
    // private moveColItemsUPOnce(cCol:number,cRow:number){

    //     //let moveItemEff:Array<any> = new Array();

    //     this.sparr_layout.children.forEach(element => {
    //         if(element.getComponent("DBLItem").col==cCol){
    //             if(this.isShowing(element.y)){
    //                 if(element.getComponent("DBLItem").row<cRow){
    //                     this.moveItemUPOnce(element);
    //     //                moveItemEff.push(element);
    //                 }
    //             }
    //         }
    //     });   

    // }

    //向上移动一格
    // private moveItemUPOnce(item:any){
    //     item.getComponent("DBLItem").row=item.getComponent("DBLItem").row+1;
    //     item.y = item.y + this.moveNextY;

    //     //移动回来  效果
    //     item.getComponent("DBLItem").curShowItem.y=item.height * -1;
    //     cc.tween(item.getComponent("DBLItem").curShowItem)
    //     .to(0.05, { position: cc.v2(0, 0) })
    //     .start();        
    // }
    private moveItemUP(rowTo:number, item:any){
        let row1:number = item.getComponent("DBLItem").row;
        let addy = (rowTo-row1)*this.moveNextY;
        item.y = item.y + addy;

        //console.log("第"+row1+"行item向上移动到："+rowTo+"行");
        
        item.getComponent("DBLItem").row=rowTo;
    }
    private moveItemTop(col:number, rowTop:number, minRowNum:number, item:any){
        for(let tmprow=rowTop; tmprow>minRowNum; tmprow--){
            let ti = this.getItemByRowAndCol(col,tmprow);
            if(ti==null){//空位置
                this.moveItemUP(tmprow,item);
                return;
            }
        }        
    }  






































    private fillBattleData(data:any){
        this.curAdCode=0;

        this.historyMaxScore = data.historyMaxScore;
        this.battleRMBCount = data.segmentNum;

        this.gameKey = data.gameKey;
        this.svalue = data.value;

        this.curRMBCount = 0;//玩家红包碎片
        this.rmb_lbl.string = this.curRMBCount+"";

        this.lbl_max_score.string = this.historyMaxScore+"";
        this.rmb_fixed_lbl.string=this.battleRMBCount+"";
    }
    private fristAddSP(){
        this.countNextRMBItemRowCol();
        //let allLv1Row:number = this.getRandomNumInt(1,this.maxRows);
        for(let y=1; y<=this.maxRows; y++){
            let highLvCol:number = this.getRandomNumInt(1,this.maxCols);
            for(let x=1; x<=this.maxCols; x++){
                //1. 运行使用
                this.addSP(y, x, cc.winSize.height/2 + this.nextScreenAddY, /*allLv1Row,*/highLvCol)

                //this.addSP(y, x, cc.winSize.height*0.7, allLv1Row,highLvCol)
                //TODO 2. 直接显示  测试使用
                //this.addSP(y, x, 0, allLv1Row,highLvCol)//位置测试
            }
            this.totalRowNum++;
        }   
        this.moveBaseSpeed = this.fastMoveBaseSpeed;
    }
    private clearGameData(){

        //依然停止
        this.stopUpate = true;


        //-------------传入参数
        //this.rmb_fixed_lbl.string = "";//关卡通关需要 获得红包数量
        //this.historyMaxScore = 0;//玩家历史最高分数
        
        //数值
        this.score_lbl.string="0";//主界面分数
        this.score_lbl2.string = "0";//暂停界面分数
        this.score_lbl3.string = "0";//结算界面分数 (结算界面)
        this.rmb_lbl.string = "0";     //游戏过程中  获得红包数量
        this.boluo_lbl.string = "0";//游戏过程中  获得菠萝的数量 (结算界面)
        this.lbl_max_com.string = "0";// 最高连击(结算界面)

        //layerout 容器
        this.sparr_layout.removeAllChildren(true);
        this.gameover_layout.active=false;
        this.gamesuspend_layout.active=false;

        
        this.curGameScore = 0;//玩家分数
        this.curGameMaxBob = 0;//玩家最高连炸数
        this.curBLCount = 0;//玩家游戏中菠萝数量
        this.curRMBCount = 0;//玩家红包碎片

        //游戏中统计限制
        this.itemBingLiveCount = 0;


        //屏幕移动相关
        this.highScreen = false;//高级屏
        this.fristScreen = true;//第一屏
        this.screenNum = 0;//屏幕数
        this.totalRowNum = 0;

        this.gameOver = false;
        this.moveGrowNum = 0;
        this.moveSpaceNum = 4;
        this.hasChangeMoveSpaceNum = false;
        this.showGameOver = false;
        this.moveBaseSpeed = 0;
        this.finishFastMoving = false;
        this.nextScreen=false;
        this.moveMult = 1;
        this.hasChangeMoveSpaceNum=false;        
    }

    //--------------------------------------------------------------------------------------
    //暂停|继续  游戏
    //--------------------------------------------------------------------------------------
    public isStopUpate(){
        return this.stopUpate;
    }
    //暂停游戏
    public doSuspendGameAction(){
        this.stopUpate = true;
        this.gamesuspend_layout.active=true;
    }
    //继续游戏
    public doContinueGameAction(){
        this.stopUpate = false;
        this.gamesuspend_layout.active=false;
    }
    //重新开始
    public doRestartGameAction(){
        this.clearGameData();
        this.fristAddSP();
        //依然停止
        this.stopUpate = false;
    }
    //返回主页
    public doGoHomeAction(){
        cc.director.loadScene("Hall");
    }































    //--------------------------------------------------------------------------------------
    //看广告  改变 chai item
    //--------------------------------------------------------------------------------------
    private curAdCode:number=0;
    private itemAd:cc.Node = null;//看广告的 chai item
    //1. 准备请求adcode
    public startWatchAdAction(itemAd:cc.Node){
        this.itemAd = itemAd;
        this.stopUpate = true;

        this.curAdCode=clearAdCode;
        this.requestAdGuide(clearAdCode)
        // cc.tween(this.node)
        // .to(0.1, {opacity: 255,scale:1})
        // .delay(5)
        // .call(() => { 
        //     this.finishWatchAdAction();
        // })
        // .start()           
    }
    //--------------------------------------------------------------------------------------
    //看广告  领取红包广告
    //--------------------------------------------------------------------------------------
    public getRMBWatchAdAction(){
        this.ad_layout.active = true;
        this.stopUpate = true;

        this.curAdCode=trmbAdCode;
        this.requestAdGuide(trmbAdCode)
        // cc.tween(this.node)
        // .to(0.1, {opacity: 255,scale:1})
        // .delay(5)
        // .call(() => { 
        //     this.finishGetRMBWatchAdAction();
        // })
        // .start()           
    }



    //2. 发送请求adcode
    private requestAdGuide(adCode: number, adGuideData: number = 0, type: number  = 0) {
        let data = <C2S_REQ_AD_CODE>{};
        let logicCenter = cc.find('LogicCenterNode').getComponent('LogicCenter');
        let user = logicCenter.getUserInfo();
        data.token = user.token;
        data.adGuideCode = adCode;
        data.adGuideData = adGuideData;
        data.type = type;
        commonPost(getAdGuideUrl, "getAdGuideHandle", data);
    }  
    //3. 请求adcode 返回
    private getAdGuideHandle(response: string) {
        let resp = JSON.parse(response);
        if (this.handleError(resp) == true) {
            cc.warn("通用错误处理");
            return;
        }

        let updateData: S2C_REQ_AD_CODE = <S2C_REQ_AD_CODE>{};
        updateData.adGuideCode = resp.data.adGuideCode;

        // updateData.adMultNum = resp.data.adMultNum;
        // updateData.adRotaryNum = resp.data.adRotaryNum;
        // updateData.sharedNum = resp.data.sharedNum;
        // updateData.adType = resp.data.type;

       this.showAd(updateData)
    }      
    //4. 显示 拉取广告请求
    public showAd(data: any) {
        if (cc.sys.WECHAT_GAME == cc.sys.platform) {

        }else if (cc.sys.isNative) {
            jsb.reflection.callStaticMethod("com/bbl/pineapple/JniHelper", "showRewardAd", "()V");
        }else {
            //todo 广告，暂时模拟onFinish
            this.ad_layout.active = true;
            let t = cc.tween;
            t(this.node)
                .delay(5)
                .call(() => {
                    NotificationCenter.Instance.emit("requestFinishAd");
                })
                .start();
        }
    }






    //看完广告才有回调
    //1. 回调收到 请求完成广告
    private requestFinishAd() {
        let data = <C2S_FINISH_AD>{};
        let logicCenter = cc.find('LogicCenterNode').getComponent('LogicCenter');
        let user = logicCenter.getUserInfo();
        data.token = user.token;
        commonPost(finishAdUrl, "finishAdHandle", data);
    }
    //2. 请求完成广告  关闭广告  返回响应
    private serviceClosedAd(response: string) {
        
        this.stopUpate = false;
        this.itemAd = null;

        if (cc.sys.WECHAT_GAME == cc.sys.platform) {

        }else if (cc.sys.isNative) {
            jsb.reflection.callStaticMethod("com/bbl/pineapple/JniHelper", "showRewardAd", "()V");
        }else {
            this.ad_layout.active = false;
        }
        
    }    
    //2. 请求完成广告  返回响应
    private finishAdHandle(response: string) {
        let resp = JSON.parse(response);
        if (this.handleError(resp) == true) {
            cc.warn("通用错误处理");
            return;
        }
        let updateData: S2C_FINISH_AD = <S2C_FINISH_AD>{};
        updateData.finishdAdCode = resp.data.finishdAdCode;
        updateData.trmb = resp.data.trmb;
        updateData.addtrmb = resp.data.addtrmb;
        
        updateData.adNum = resp.data.adNum;
        updateData.tfAdNum = resp.data.tfAdNum;
        
        updateData.serverTime = resp.serverTime;
        //NotificationCenter.Instance.emit(S2CProtocol.s2c_finish_ad, updateData);
        this.finishAd(updateData)
    }
    //改变 返回值
    private finishAd(data: any) {
        let logicCenter = cc.find('LogicCenterNode').getComponent('LogicCenter');
        let user = logicCenter.getUserInfo();
        if (data.adNum != null && data.adNum != undefined) {
            user.adNum = data.adNum;
        }
        if (data.tfAdNum != null && data.tfAdNum != undefined) {
            user.tfAdNum = data.tfAdNum;
        }
        user.adCD = adCoolDur;
        user.trmb = data.trmb;
        switch (data.finishdAdCode) {
            case clearAdCode:
                {
                    this.finishWatchAdAction();
                }
                break;
            case trmbAdCode:
                {
                    this.finishGetRMBWatchAdAction()
                }
                break;                
            }
    }


    //5. 看完广告  领取红包   完成
    public finishGetRMBWatchAdAction(){
        this.ad_layout.active = false;
        this.stopUpate = false;
    }
    //5. 看完广告清楚  障碍物   完成
    public finishWatchAdAction(){
        this.ad_layout.active = false;
        if(this.itemAd!=null){
            cc.tween(this.itemAd)
            .repeat(3,
                cc.tween().to(0.1, {opacity: 100,scale:0.8})
                            .to(0.1, {opacity: 255,scale:1})
                )  
            .call(() => { 
                this.ad_layout.active = false;
                let moveCol:number = this.itemAd.getComponent("DBLItem").col;
                let moveRow:number = this.itemAd.getComponent("DBLItem").row;
                this.sparr_layout.removeChild(this.itemAd,true)
                this.moveColItemsUPOnceByStep(moveCol,moveRow-1);
            })
            .start()           
        }
    }
    












































    //--------------------------------------------------------------------------------------
    //出瓜规则
    //--------------------------------------------------------------------------------------
    
    //出红包的规则-----------------------------------------------------
    private addRondomRMBItemRow:number = 4;//增加的行
    private rondomRMBItemRowFloatedNum:number = 4;//增加的行
    private rondomRMBItemRowNum:number = 8;//出红包的行 = 8+random(0,4)

    private nextRMBItemRow:number = 0;
    private nextRMBItemCol:number = 0;

    private countNextRMBItemRowCol(){
        let tmpRow:number = this.getRandomNumInt(0,this.rondomRMBItemRowFloatedNum);
        this.nextRMBItemRow = this.rondomRMBItemRowNum+tmpRow;
        this.nextRMBItemCol = this.getRandomNumInt(1,this.maxCols);
    }
    private isRMBItemRowCol(row:number, col:number){
        if(this.curRMBCount>=this.battleRMBCount){
            return false;
        }
        if(  ((this.totalRowNum+1)%this.nextRMBItemRow==0)   &&   col==this.nextRMBItemCol){
            this.nextRMBItemRow = 0;
            this.nextRMBItemCol = 0;          
            return true;
        }
        return false;
    }
    //出红包的规则-----------------------------------------------------


    //出冰瓜的规则-----------------------------------------------------
    private nextBingItemRow:number =0;
    private nextBingItemCol:number =0;
    private countNextBingItemRowCol(){
        this.nextBingItemRow =0;
        this.nextBingItemCol =0;    

        if(this.itemBingLiveCount<3){
            let tmpData:number = this.getRandomNumInt(0,100);
            if(tmpData<=33){
                let repeat:boolean = false;
                this.nextBingItemCol = this.getRandomNumInt(1,this.maxCols);
                do{
                    this.nextBingItemRow = this.getRandomNumInt(2,this.maxRows);
                    if(this.nextBingItemRow==this.nextRMBItemRow && this.nextBingItemCol==this.nextRMBItemCol){
                        repeat = true; 
                    }else{
                        repeat = false;
                    }
                }while(repeat);
            }
        }
    }
    private isBingItemRowCol(row:number, col:number){
        if(this.itemBingLiveCount>=3){
            return false;
        }
        if(  ((this.totalRowNum+1)%this.nextBingItemRow==0)   &&   col==this.nextBingItemCol){
            this.nextBingItemRow =0;
            this.nextBingItemCol =0;  
            return true;
        }
        return false;
    }
    //出冰瓜的规则-----------------------------------------------------


    private getRandomNumInt(min: number, max: number) {
        var Range = max - min;
        var Rand = Math.random(); //获取[0-1）的随机数
        return (min + Math.round(Rand * Range)); //放大取整
    }
    private randItemId(row:number, col:number, highLvCol:number){
        let tmpId:number = 1;

        // if(true){
        //     return DBLItem.ID_1;
        // }

        if(this.isRMBItemRowCol(row, col)){
            tmpId = DBLItem.ID_RMB;
            console.log("红包出现row： "+row+" col:"+col);
            return tmpId;
        }

        if(this.isBingItemRowCol(row, col)){
            this.itemBingLiveCount++;
            tmpId = DBLItem.ID_BING;
            console.log("冰西瓜出现row： "+row+" col:"+col);
            return tmpId;
        }

        //TODO 方法重构
        if(col==highLvCol || this.highScreen){
            let lv:number = this.getRandomNumInt(1,100);
            if(this.highScreen){
                if(row%2==0){
                    if(lv<=15){
                        tmpId = DBLItem.ID_CHAI;
                    }else if(lv<=30){
                        tmpId = DBLItem.ID_3;
                    }else if(lv<=65){
                        tmpId = DBLItem.ID_2;
                    }else{
                        tmpId = DBLItem.ID_1;
                    }
                }else{
                    if(lv<=40){
                        tmpId = DBLItem.ID_2;
                    }else{
                        tmpId = DBLItem.ID_1;
                    } 
                }
            }else{
                if(lv>20){
                    //sp = cc.instantiate(this.sprit2);
                    tmpId = DBLItem.ID_2;
                }else{
                    //sp = cc.instantiate(this.sprit3);
                    tmpId = DBLItem.ID_3;
                }
            }
        }else{
            //sp = cc.instantiate(this.sprit1);
            tmpId = DBLItem.ID_1;
        }
        return tmpId;
    }
    //--------------------------------------------------------------------------------------
    //出瓜规则
    //--------------------------------------------------------------------------------------    




    //--------------------------------------------------------------------------------------
    //服务器交互
    //--------------------------------------------------------------------------------------
    private handleError(response: any) {
        if (response.code != 200) {
            console.log("服务器错误提示："+response.msg);
            return true;
        }

        return false;
    }    
    private requestGoFighting(){
        let data:any = {};
        let logicCenter = cc.find('LogicCenterNode').getComponent('LogicCenter');
        let user = logicCenter.getUserInfo();
        data.token = user.token;
        commonPost(goFightingUrl, "goFightingHandler", data);
    }
    public goFighting(response:string){
        let resp = JSON.parse(response);
        if (this.handleError(resp) == true) {
            cc.warn("通用错误处理");

            NotificationCenter.Instance.emit(L2EProtocol.l2e_login_error, resp.msg);
            return;
        }        
        this.fillBattleData(resp.data);
        this.fristAddSP();
        this.stopUpate=false;
    }
    private requestBattleResult(){
        let data:any = {};
        let logicCenter = cc.find('LogicCenterNode').getComponent('LogicCenter');
        let user = logicCenter.getUserInfo();
        data.token = user.token;
        data.segmentNum = this.curRMBCount;
        data.score = this.curGameScore;
        data.bl = this.curBLCount;
        data.value = this.svalue;
        data.sign = "";
        commonPost(battleResultUrl, "battleResultHandle", data);
    }    
    public battleResult(response:string){
        let resp = JSON.parse(response);
        if (this.handleError(resp) == true) {
            cc.warn("通用错误处理");

            NotificationCenter.Instance.emit(L2EProtocol.l2e_login_error, resp.msg);
            return;
        }        
        this.fillBattleData(resp.data);
        if(resp.data.win==1){
            //1. 弹广告。 红包收集完返回
            this.getRMBWatchAdAction()
        }else{
            //1. gamover
            this.gameover_layout.active=true;
        }
    }
}
